package com.wn.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wn.pojo.Order;
import com.wn.service.IOrderService;
import com.wn.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author yellow Docter
 * @date 2023 -06-28
 * @desc
 */
@Controller
@RequestMapping("/pay")
public class PayController extends BaseController {


    //沙箱账号: etocku4296@sandbox.com
    //密码:    111111
    //支付宝网关（固定）
    public static final String SAVE_URL = "https://openapi.alipaydev.com/gateway.do";

    //APPID 即创建应用后生成。ctrl + shift + U
    public static final String APPID = "2021000120620148";

    //私钥
    public static final String PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCAlhzeFAqyf2ONenlTjaOJuwmjWeM0ujgzCTMIDwgacsFbGmHoh3M66JWpcRdPYG4RV13RODrBJFEPaWV8S4R13m7P0sZtzB3bVHTHTuZiTHaRZPr+EWcMY6HRtgAWpz0JAXYOTVDGkNhSeGxScOCnzPzirhC0+YBcTmIrqxpcgqwdGADK/9EbVBUg+3BqBMPbbAjxE2pXo0dc6IfoBIkVVPnZtuS1VnTVoBhvpu7HO/h6VaMCn/fw/Fin+Hr0Zg3IU5zIgjEw4GW9oaHAF/uW4MNRdUhRo+esdQ2sSqAKf4DpNOx2r+5D5kkWTGUk+3z1ZHxyp3PBTEFQvKiC/r81AgMBAAECggEADYtCOSYVRl3ip4lJ9EIMArrftgQGyYv/1WhXpramnNqPgUATJgH2YjMTaIiP8v1uOodgS2RH1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iEcpWWLg75XLYgPTqzXZ+7/enMpmHrAMfUy1jfgOtMuYHMonCSja/FdHt/vqJi7DO8g1uLfz1zC0KA==";

    //支付宝公钥
    public static final String ALI_PAYPUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjU+upv91El5tv7U503xBdXatySZTO527nagSVcxx6N9rIOd4zgBIfUpB5TZZZ88mq2hyICfouB0Ofv6P1K328b1WGum6avpEPQ4qRNMW7u2QIzPFB5hHwTFfUrS0vGRS9h9oWfqMBbgbOFojt7cFDyBwx30Obz8J6ZO8GW8jqiVuy5kBAle8+bfL6r6E3pZ8CKimQUjXjhVojkdj2AA0UNZt/9+9UszlpMqZThZ0Fnwalwoe/TGTKYNxIINvrrYMIHb3YnPwiYPr0CqI9udeMKk+UKC3U47DC7qqRdJf5c2dvDptldcELEbIMKBKzK61DdLWDpO6NpbgJ2EqyZGoTwIDAQAB";

    @Autowired
    private IOrderService orderService;

    @PostMapping("/{orderId}")
    @ResponseBody
    public Result pay(@PathVariable("orderId") Long orderId) throws AlipayApiException {

        //01 查询订单信息
        Order order = orderService.getById(orderId);

        //1、创建AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                SAVE_URL,            //支付宝网关（固定）。
                APPID,              //APPID 即创建应用后生成。
                PRIVATE_KEY,        //私钥
                "json",
                "utf-8",
                ALI_PAYPUBLIC_KEY,  //公钥
                "RSA2");            //加密方式
        //2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        //http://wrifvp.natappfree.cc
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl("http://wrifvp.natappfree.cc/pay/notifyUrl");

        //同步跳转地址，仅支持http/https
        request.setReturnUrl("http://wrifvp.natappfree.cc/pay/returnUrl");

        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", orderId);
        //支付金额，最小值0.01元
        bizContent.put("total_amount", order.getPrice());
        //订单标题，不可使用特殊符号
        bizContent.put("subject", order.getCourseId());
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());

        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        String form = response.getBody();
        System.out.println(form);
        if (response.isSuccess()) {
            return toDataResult(form);
        } else {
            return toDataResult(form);
        }
    }

    /**
     * 异步操作
     * 支付成功后、通知服务器、修改 订单的 状态
     *
     * @param request
     * @return
     */
    @PostMapping("/notifyUrl")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request) {
        System.out.println("回调通知....==============>");

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }

            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, ALI_PAYPUBLIC_KEY, "UTF-8"); // 验证签名

            //如果验签失败
            if (!checkSignature) {
                return "fail";
            }
            //验签成功后
            //商户的业务逻辑  比如修改订单号
            System.out.println("修改订单成功");

            //商户订单号
            String outTradeNo = params.get("out_trade_no");
            System.out.println("outTradeNo = " + outTradeNo);

            //支付宝交易凭证号
            String alipayTradeNo = params.get("trade_no");
            System.out.println("alipayTradeNo = " + alipayTradeNo);

            // 查询订单
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", outTradeNo);   //通过订单编号 查询
            Order order = orderService.getOne(queryWrapper);

            //修改订单
            if (order != null) {
                order.setTradeNo(alipayTradeNo);  //交易号
                order.setPayTime(new Date());     //付款时间
                order.setStatus(2);               //付款状态
                orderService.updateById(order);   //更新订单
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 同步操作  告诉支付跳转到 那个页面 (前端页面)
     *
     * @return
     */
    @GetMapping("/returnUrl")
    public String returnUrl() {
        /**
         * 这里不写具体的业务逻辑只做一个页面的跳转
         */
        return "redirect:http://localhost:8081";
    }
}
